
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>

static struct termios savedterm;

int init_term()
{

	char *tty;
	FILE *fp;
	int   fd;
	struct termios term;

	tty = ctermid(NULL);
	if(!tty)
		return 0;
		
	fp = fopen(tty, "r+");
	if(fp)
	{
		setbuf(fp, NULL);

		fd = fileno(fp);
		if(tcgetattr(fd, &term) == 0)
		{
			savedterm = term;

			term.c_lflag &= ~(ECHO | ICANON);
			term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
			term.c_oflag &= ~(OPOST);
			term.c_cflag &= ~(CSIZE | PARENB);
			term.c_cflag |= CS8;
			term.c_cc[VMIN] = 1;
			term.c_cc[VTIME] = 0;

			if(tcsetattr(fd, TCSAFLUSH, &term) == 0)
			{
				fclose(fp);
				return 1;
			}
			
			tcsetattr(fd, TCSAFLUSH, &savedterm);
		}
	}

	fclose(fp);
	return 0;
}

int restore_term()
{
	char *tty;
	int   fd;
	
	tty = ctermid(NULL);
	if(tty)
		return 0;
		
	fd = open(tty, O_RDWR);
	if(fd)
	{
		if(tcsetattr(fd, TCSAFLUSH, &savedterm))
		{
			close(fd);
			return 1;
		}
	}

	close(fd);
	return 1;
}


int readline()
{
	int c;
	char ch;

	printf("dshell> ");
	for(;;)
	{
		c = getc(stdin);
		printf("|%x|", c);
		if(c == 'z')
			printf("%c", 0x08);
	//	if(c >= 'A' && c <= 'Z')
	//		goto swalow;
	//	switch(c)
	//	{
	//		case 'b':
	//	}
	}
	return 0;
}

int main()
{
	if(init_term())
	{
		readline();
		restore_term();
	}

	return 1;
}
